package person.drf.shop.product.jucTest;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class ForkJoinDemoTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test3();
    }

    //普通求和
    public static void test1(){
        long startTime = System.currentTimeMillis();

        Long sum = 0L;
        for (Long i = 1L; i <= 10_0000_0000; i++) {
            sum+=i;
        }
        System.out.println("普通求和结果"+sum);
        long endTime = System.currentTimeMillis();
        System.out.println("普通求和test1所用时间"+(endTime-startTime));
    }

    //使用forkjoin
    public static void test2() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L,10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);   //提交结果
        System.out.println("test2结果"+submit.get());

        long endTime = System.currentTimeMillis();
        System.out.println("forkjoin求和test2所用时间"+(endTime-startTime));
    }


    //stream并行流
    public static void test3(){
        long startTime = System.currentTimeMillis();
        Long sum = LongStream.range(0L,10_0000_0000L).reduce(0,Long::sum);
        System.out.println("test3结果"+sum);
        long endTime = System.currentTimeMillis();
        System.out.println("并行流test3所用时间"+(endTime-startTime));
    }

}
